{% extends "admin/base.html" %}

{% block title %}{{ '编辑量表' if scale_id else '创建量表' }}{% endblock %}

{% block extra_css %}
<style>
.form-section {
    background-color: #f8f9fa;
    border-radius: 0.375rem;
    padding: 1.5rem;
    margin-bottom: 1.5rem;
}

.section-title {
    color: #495057;
    font-weight: 600;
    margin-bottom: 1rem;
    border-bottom: 2px solid #dee2e6;
    padding-bottom: 0.5rem;
}

.required {
    color: #dc3545;
}

.form-label {
    font-weight: 500;
}

.btn-back {
    margin-right: 1rem;
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-0">{{ '编辑量表' if scale_id else '创建量表' }}</h1>
            <p class="text-muted mb-0">{{ '修改量表基本信息和设置' if scale_id else '创建新的心理量表' }}</p>
        </div>
        <div>
            <a href="/admin/scales" class="btn btn-outline-secondary btn-back">
                <i class="bi bi-arrow-left me-1"></i>返回列表
            </a>
        </div>
    </div>

    <!-- 表单区域 -->
    <form id="scaleForm">
        <input type="hidden" id="scaleId" value="{{ scale_id or '' }}">
        
        <!-- 基本信息 -->
        <div class="form-section">
            <h5 class="section-title">基本信息</h5>
            <div class="row">
                <div class="col-md-8">
                    <div class="mb-3">
                        <label for="title" class="form-label">量表标题 <span class="required">*</span></label>
                        <input type="text" class="form-control" id="title" required>
                        <div class="form-text">请输入清晰描述量表用途的标题</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="mb-3">
                        <label for="version" class="form-label">版本号</label>
                        <input type="text" class="form-control" id="version" value="1.0">
                    </div>
                </div>
            </div>
            
            <div class="mb-3">
                <label for="subtitle" class="form-label">副标题</label>
                <input type="text" class="form-control" id="subtitle">
                <div class="form-text">可选，用于进一步说明量表内容</div>
            </div>
            
            <div class="mb-3">
                <label for="description" class="form-label">量表描述 <span class="required">*</span></label>
                <textarea class="form-control" id="description" rows="4" required></textarea>
                <div class="form-text">详细描述量表的用途、测量内容和适用对象</div>
            </div>
            
            <div class="mb-3">
                <label for="instruction" class="form-label">测试说明</label>
                <textarea class="form-control" id="instruction" rows="3"></textarea>
                <div class="form-text">向测试者说明如何完成量表，包括注意事项</div>
            </div>
        </div>

        <!-- 分类和权限设置 -->
        <div class="form-section">
            <h5 class="section-title">分类和权限</h5>
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="category" class="form-label">分类 <span class="required">*</span></label>
                        <select class="form-select" id="category" required>
                            <option value="">请选择分类</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="memberLevel" class="form-label">最低会员级别</label>
                        <select class="form-select" id="memberLevel">
                            <option value="basic">基础会员</option>
                            <option value="professional">专业会员</option>
                            <option value="institution">机构会员</option>
                            <option value="research">科研会员</option>
                        </select>
                        <div class="form-text">设置使用此量表所需的最低会员级别</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 测试设置 -->
        <div class="form-section">
            <h5 class="section-title">测试设置</h5>
            <div class="row">
                <div class="col-md-4">
                    <div class="mb-3">
                        <label for="estimatedTime" class="form-label">预估时间（分钟）</label>
                        <input type="number" class="form-control" id="estimatedTime" min="1" max="120">
                        <div class="form-text">完成量表大概需要的时间</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="mb-3">
                        <label for="status" class="form-label">发布状态</label>
                        <select class="form-select" id="status">
                            <option value="DRAFT">草稿</option>
                            <option value="PUBLISHED">已发布</option>
                            <option value="ARCHIVED">已归档</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="mb-3">
                        <div class="form-check mt-4">
                            <input class="form-check-input" type="checkbox" id="isPublic" checked>
                            <label class="form-check-label" for="isPublic">
                                公开量表
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="isFree" checked>
                            <label class="form-check-label" for="isFree">
                                免费使用
                            </label>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 作者信息 -->
        <div class="form-section">
            <h5 class="section-title">作者信息</h5>
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="author" class="form-label">作者</label>
                        <input type="text" class="form-control" id="author">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="copyright" class="form-label">版权信息</label>
                        <textarea class="form-control" id="copyright" rows="2"></textarea>
                    </div>
                </div>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="d-flex justify-content-end gap-2 mb-4">
            <a href="/admin/scales" class="btn btn-secondary">
                <i class="bi bi-x-circle me-1"></i>取消
            </a>
            <button type="button" class="btn btn-success" onclick="saveScale()">
                <i class="bi bi-check-circle me-1"></i>{{ '更新量表' if scale_id else '创建量表' }}
            </button>
            {% if scale_id %}
            <a href="/admin/scale-design?id={{ scale_id }}" class="btn btn-primary">
                <i class="bi bi-list-ol me-1"></i>设计题目
            </a>
            {% endif %}
        </div>
    </form>
</div>
{% endblock %}

{% block extra_js %}
<script>
let isEditMode = false;

document.addEventListener('DOMContentLoaded', function() {
    // 检查管理员token
    const adminToken = localStorage.getItem('adminToken');
    if (!adminToken) {
        showAlert('请先登录管理员账户', 'error');
        setTimeout(() => {
            window.location.href = '/admin-portal';
        }, 2000);
        return;
    }
    
    loadCategories();
    
    // 如果是编辑模式，加载量表数据
    const scaleId = document.getElementById('scaleId').value;
    if (scaleId) {
        isEditMode = true;
        loadScaleData(scaleId);
    }
});

// 加载分类列表
function loadCategories() {
    fetch('/api/admin/scales/categories', {
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const categorySelect = document.getElementById('category');
            categorySelect.innerHTML = '<option value="">请选择分类</option>';
            
            data.data.categories.forEach(category => {
                const option = `<option value="${category.id}">${category.name}</option>`;
                categorySelect.innerHTML += option;
            });
        }
    })
    .catch(error => console.error('加载分类失败:', error));
}

// 加载量表数据（编辑模式）
function loadScaleData(scaleId) {
    fetch(`/api/admin/scales/${scaleId}`, {
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const scale = data.data;
            
            // 填充表单
            document.getElementById('title').value = scale.title || '';
            document.getElementById('subtitle').value = scale.subtitle || '';
            document.getElementById('description').value = scale.description || '';
            document.getElementById('instruction').value = scale.instruction || '';
            document.getElementById('category').value = scale.category_id || '';
            document.getElementById('memberLevel').value = scale.min_member_level || 'basic';
            document.getElementById('estimatedTime').value = scale.estimated_time || '';
            document.getElementById('status').value = scale.status || 'DRAFT';
            document.getElementById('isPublic').checked = scale.is_public;
            document.getElementById('isFree').checked = scale.is_free;
            document.getElementById('version').value = scale.version || '';
            document.getElementById('author').value = scale.author || '';
            document.getElementById('copyright').value = scale.copyright_info || '';
        } else {
            showAlert('加载量表数据失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('加载量表数据失败:', error);
        showAlert('加载量表数据失败', 'error');
    });
}

// 保存量表
function saveScale() {
    // 验证必填字段
    const title = document.getElementById('title').value.trim();
    const description = document.getElementById('description').value.trim();
    const categoryId = document.getElementById('category').value;
    
    if (!title) {
        showAlert('请输入量表标题', 'warning');
        return;
    }
    
    if (!description) {
        showAlert('请输入量表描述', 'warning');
        return;
    }
    
    if (!categoryId) {
        showAlert('请选择量表分类', 'warning');
        return;
    }
    
    // 收集表单数据
    const formData = {
        title: title,
        subtitle: document.getElementById('subtitle').value.trim(),
        description: description,
        instruction: document.getElementById('instruction').value.trim(),
        category_id: parseInt(categoryId),
        min_member_level: document.getElementById('memberLevel').value,
        estimated_time: document.getElementById('estimatedTime').value ? parseInt(document.getElementById('estimatedTime').value) : null,
        status: document.getElementById('status').value,
        is_public: document.getElementById('isPublic').checked,
        is_free: document.getElementById('isFree').checked,
        version: document.getElementById('version').value.trim(),
        author: document.getElementById('author').value.trim(),
        copyright_info: document.getElementById('copyright').value.trim(),
        price: 0.0
    };
    
    const scaleId = document.getElementById('scaleId').value;
    const url = isEditMode ? `/api/admin/scales/${scaleId}` : '/api/admin/scales';
    const method = isEditMode ? 'PUT' : 'POST';
    
    // 发送请求
    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert(isEditMode ? '量表更新成功' : '量表创建成功', 'success');
            
            // 如果是创建模式，跳转到编辑页面
            if (!isEditMode && data.data && data.data.scale_id) {
                setTimeout(() => {
                    window.location.href = `/admin/scale-edit?id=${data.data.scale_id}`;
                }, 1500);
            }
        } else {
            showAlert((isEditMode ? '更新' : '创建') + '失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('保存失败:', error);
        showAlert((isEditMode ? '更新' : '创建') + '失败', 'error');
    });
}

function showAlert(message, type = 'info') {
    const alertClass = type === 'error' ? 'alert-danger' : 
                      type === 'success' ? 'alert-success' : 
                      type === 'warning' ? 'alert-warning' : 'alert-info';
    
    const alertHTML = `
        <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    // 在页面顶部显示提示
    const container = document.querySelector('.container-fluid');
    container.insertAdjacentHTML('afterbegin', alertHTML);
    
    // 3秒后自动消失
    setTimeout(() => {
        const alert = container.querySelector('.alert');
        if (alert) {
            bootstrap.Alert.getOrCreateInstance(alert).close();
        }
    }, 3000);
}
</script>
{% endblock %} 